import { TypingContentTypeEnum, TypingModeEnum } from '@renderer/enums/TypingEnum'
import { useTypingStoreHook } from '@renderer/store/index'

// 定义TgChineseWords组件的类型
interface TgChineseWordsInstance {
  focusCurrentInput: () => void
  setIgnoreNextInput?: (value: boolean) => void
}

interface TgChineseSentencesInstance {
  focusCurrentInput: () => void
  setIgnoreNextInput?: (value: boolean) => void
}

interface TgEnglishWordsInstance {
  focusCurrentInput: () => void
  setIgnoreNextInput?: (value: boolean) => void
}

interface TgEnglishSentencesInstance {
  focusCurrentInput: () => void
  setIgnoreNextInput?: (value: boolean) => void
}

export default (
  tgChineseWordsInstance: Ref<TgChineseWordsInstance | null>,
  tgChineseSentencesInstance: Ref<TgChineseSentencesInstance | null>,
  tgEnglishWordsInstance: Ref<TgEnglishWordsInstance | null>,
  tgEnglishSentencesInstance: Ref<TgEnglishSentencesInstance | null>
) => {
  const typingStore = useTypingStoreHook()
  // 全局快捷键
  window.addEventListener('keydown', (e) => {
    switch (e.key || e.code) {
      case 'Tab':
        e.preventDefault()
        // 如果打字已暂停，则重置测试
        if (typingStore.isPaused) {
          typingStore.resetTyping()
          tgChineseWordsInstance.value?.focusCurrentInput()
        } else {
          // 如果打字未暂停，则暂停打字
          typingStore.pauseTyping()
        }
        break
      case 'Enter':
        e.preventDefault()
        // 如果打字已暂停，则重置测试
        if (typingStore.isPaused) {
          typingStore.resetTyping()
          focusCurrentInput()
        }
        break
      case 'Space':
      case ' ':
        // 如果打字已暂停，则重新开始当前测试
        if (typingStore.isPaused) {
          e.preventDefault()
          typingStore.redoTyping()
          focusCurrentInput()
        }
        break
      default:
        // 如果打字已暂停，则恢复打字
        if (typingStore.isPaused) {
          typingStore.resumeTyping()
          focusCurrentInput()
        }
        break
    }
  })

  const focusCurrentInput = () => {
    switch (typingStore.mode) {
      case TypingModeEnum.CHINESE:
        if (typingStore.contentType === TypingContentTypeEnum.WORD) {
          tgChineseWordsInstance.value?.focusCurrentInput()
        } else {
          tgChineseSentencesInstance.value?.focusCurrentInput()
        }
        break
      case TypingModeEnum.ENGLISH:
        if (typingStore.contentType === TypingContentTypeEnum.WORD) {
          tgEnglishWordsInstance.value?.focusCurrentInput()
        } else {
          tgEnglishSentencesInstance.value?.focusCurrentInput()
        }
        break
    }
  }
}
